package daily;

/**
 * @author MtRider
 * @version 1.0
 * @description 删除链表的倒数第N个节点
 * @GiteeAndGithub MtRider
 * @date 2022/4/27 15:34
 */
public class demo18 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre=head;
        int last=getLength(head)-n;
        if(last ==0){
            return head.next;
        }

        for (int i = 0; i < last - 1; i++) {
            pre=pre.next;
        }
        pre.next=pre.next.next;
        return head;
    }

    public int getLength(ListNode head){
        int length=0;
        while(head!=null){
            length++;
            head=head.next;
        }
        return length;
    }
}
